﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using MyCompany.WebCrawler.Repositories;
using MyCompany.WebCrawler.Tasks.Tasks;

namespace MyCompany.WebCrawler.Tasks
{
    public class ThreadManager
    {
        private IRepository repository;
        List<Thread> workers;

        public ThreadManager(IRepository repository)
        {
            this.repository = repository;
        }

        public void Start(int threadCounts)
        {
            workers = new List<Thread>();

            for (int i = 0; i < threadCounts; i++)
            {
                var worker = new Thread(Consume);
                workers.Add(worker);
                worker.Name = i.ToString();
                worker.Start(repository);
            }

        }

        internal void Stop()
        {
            ;
        }

        private void Consume(object repository)
        {
            while (true)
            {
                try
                {
                    var queue = (repository as Repository).Queue;
                    var task = queue.Denqueue();
                    task.Execute();

                    if (task is FinishTask)
                        return;
                }
                catch (Exception e)
                {
                    Trace.WriteLine("EXCEPTION: " + e);
                }
            }
        }


        public void Wait()
        {
            var queue = repository.Queue;
            workers.ForEach(x => queue.Enqueue(new FinishTask()));

            foreach (var worker in workers)
                worker.Join();
        }
    }
}
